﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace MediaStreamer
{
    public class Server
    {
        protected int _port = 80;
        protected Thread _thread;

        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public int Port
        {
            get { return _port; }
        }

        public bool IsAlive { get { return (_thread != null ? _thread.IsAlive : false); } }

        public Server(int port)
        {
            _port = port;
            _thread = new Thread(OnStart);
        }

        public void Start()
        {
            _thread.Start();
        }

        protected static void HandleConnection(Socket socket)
        {
            var t = new Thread(Client.HandleRequest);
            t.IsBackground = true;
            t.Start(socket);
        }

        protected void OnStart()
        {
            PageHandler.EnsureIndexesAndStaticItems();

            //var pages = PageHandler.GetPages();
            //Storage.AddPages(pages);

            Console.WriteLine("Start listening on port 80.");
            try
            {
                var socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

                socket.Bind(new IPEndPoint(IPAddress.Any, _port));
                socket.Listen(100);

                while (IsAlive)
                {
                    allDone.Reset();

                    Console.WriteLine("listening.");
                    socket.BeginAccept(new AsyncCallback(OnAccept), socket);

                    allDone.WaitOne();
                }

                Console.WriteLine("Not listening anymore for some reason.");
            }
            catch(ThreadAbortException)
            {
                
            }
        }

        protected static void OnAccept(IAsyncResult ar)
        {
            allDone.Set();

            var listener = (Socket)ar.AsyncState;
            var handler = listener.EndAccept(ar);

            HandleConnection(handler);
        }

        public void Stop()
        {
            if (_thread != null)
            {
                Console.WriteLine("Stopping server.");
                _thread.Abort();
            }
        }
    }
}
